package com.store.service.impl;

import com.store.dto.request.CategoryRequest;
import com.store.entity.Category;
import com.store.mapper.CategoryMapper;
import com.store.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category findById2(Long id) {
        return null;
    }

    @Override
    public Category create2(CategoryRequest request) {
        return null;
    }

    @Override
    public List<Category> getList(Integer page, Integer pageSize, String keyword) {
        int offset = (page - 1) * pageSize;
        if (keyword != null && !keyword.trim().isEmpty()) {
            return categoryMapper.selectListByKeyword(keyword, offset, pageSize);
        }
        return categoryMapper.selectList(offset, pageSize);
    }

    @Override
    public Category findById(Long id) {
        return categoryMapper.selectById(id);
    }

    @Override
    @Transactional
    public Category create(CategoryRequest request) {
        if (request == null) {
            throw new RuntimeException("请求参数不能为空");
        }
        if (request.getCategoryName() == null || request.getCategoryName().trim().isEmpty()) {
            throw new RuntimeException("分类名称不能为空");
        }
        
        Category category = new Category();
        category.setCategoryName(request.getCategoryName().trim());
        category.setDescription(request.getDescription());
        
        LocalDateTime now = LocalDateTime.now();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        
        categoryMapper.insert(category);
        return category;
    }

    @Override
    @Transactional
    public Category update(Long id, CategoryRequest request) {
        Category category = categoryMapper.selectById(id);
        if (category == null) {
            throw new RuntimeException("分类不存在");
        }
        
        if (request.getCategoryName() == null || request.getCategoryName().trim().isEmpty()) {
            throw new RuntimeException("分类名称不能为空");
        }
        
        category.setCategoryName(request.getCategoryName().trim());
        category.setDescription(request.getDescription());
        category.setUpdateTime(LocalDateTime.now());
        
        categoryMapper.update(category);
        return category;
    }

    @Override
    @Transactional
    public void delete(Long id) {
        categoryMapper.deleteById(id);
    }

    @Override
    public List<Category> getAll() {
        return categoryMapper.selectAll();
    }
} 